package com.lfy.kcat.user.interceptor;

import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.enums.FeignEnum;
import org.dromara.common.core.exception.ServiceException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * Feign的响应解码器，负责解码 Feign客户端 收到的响应数据
 * 统一响应解码器，自己判断成功失败。业务不用管远程
 * @author leifengyang
 * @version 1.0
 * @date 2025/9/19 10:16
 * @description:
 */
@Component
@Slf4j
public class FeignResponseDecoder extends SpringDecoder {

    public FeignResponseDecoder(ObjectFactory<HttpMessageConverters>
                                    messageConverters) {
        super(messageConverters);
    }


    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        Object decode = super.decode(response, type);
        log.info("获取到的响应数据: {}", decode);
        if(decode instanceof R){
            R<?> r = (R<?>) decode;
            if(r.getCode()!=200){
                throw new ServiceException(r.getMsg(), r.getCode());
            }
        }
        return decode;
    }
}
